//
//  AppDelegate.m
//  baodongPro
//
//  Created by feng on 15/11/17.
//  Copyright © 2015年 proper. All rights reserved.
//




#define APPID_VALUE @"56d67e40"
#define TIMEOUT_VALUE         @"20000"
#import "AppDelegate.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

#import "iflyMSC/IFlySpeechUtility.h"
#import "IFlyFlowerCollector.h"
#import "iflyMSC/iflySetting.h"
#import "MineViewController.h"
#import "MainViewController.h"

#import "UIView+FBDQuickCreateUI.h"
#import "FBD_FMDBTool.h"
#import "AppDefineHeader.h"
#import <FBDTools/ShowAlertTool.h>



@interface AppDelegate ()<EMContactManagerDelegate,UIAlertViewDelegate>
@property (nonatomic,strong)MainViewController*viewVC;
@property (nonatomic,strong)MineViewController*myIPhoneVC;
@property (nonatomic,strong)FBDTabBarViewController* myTabBarVC;
@property (nonatomic,strong)FBDMenuViewController  * myMenuVC;
@property (nonatomic,strong)LoginViewController * loginVC;
@property (nonatomic,strong)CLLocationManager *locationManage;

@end

@implementation AppDelegate
{
    NSString* _agreeUserId;

}


// 快速获取自定义TabBarViewController
-(FBDTabBarViewController*)fbd_tabBarVC
{
    if (!_myTabBarVC)
    {
        _myTabBarVC=[[FBDTabBarViewController alloc] init];
        [_myTabBarVC  setupUnreadMessageCount];
        
    }
        _myTabBarVC.tabBar.barTintColor=  NavgationBarColor;
    return _myTabBarVC;

}

// 快速获取自定义FBDMenuViewController
-(FBDMenuViewController*)fbd_menuVC
{

    if (!_myMenuVC)
    {
        _myMenuVC=[[FBDMenuViewController alloc] init];
    }
    return _myMenuVC;

}
// 快速获取登录的LoginVC
-(LoginViewController*)fbd_loginVC
{
    if (!_loginVC)
    {
        _loginVC=[[LoginViewController alloc] init];
    }
    return _loginVC;

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self configeClientSetting];
    self.window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    //AppKeyapplicationDidEnterBackground:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    
//    EMOptions *options =[EMOptions optionsWithAppkey:HuanAPPKEY];
//    options.apnsCertName = CenterAPNS;
//    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    // 配置讯飞语音
    [self    configeIFlySpeech];
    // 定位服务
    [self    beginLocationServer];

    
    [self fbd_tabBarVC];
    if (!_loginVC)
    {
        _loginVC=[[LoginViewController alloc] init];
        
    }

     [UMSocialData setAppKey:@"56e23ecee0f55af03b000a7e"];

//    [UMSocialData openLog:YES];
    
    //设置微信AppId、appSecret，分享url
//   [UMSocialWechatHandler setWXAppId:@"wxa9eef8a5ca53ce2a" appSecret:@"8b909b47369db4b2bdab5135cb0eb94f" url:@"https://git.oschina.net/donggehaoya/MyDaughter"];
    [UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"https://git.oschina.net/donggehaoya/MyDaughter"];

    
    [UMSocialQQHandler setQQWithAppId:@"1103841572" appKey:@"RYsduFxiqWY511Lv" url:@"http://git.oschina.net/donggehaoya/MyDaughter"];

    

    NSDictionary*dicOption=@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:NO]};
    [[EaseSDKHelper shareHelper] hyphenateApplication:application didFinishLaunchingWithOptions:launchOptions appkey:HuanAPPKEY apnsCertName:HuanCenterAPNS otherConfig:dicOption];
    

    
    
    // 配置NavgationBar
    [self configeNavgationBar];

    [FBDClientTool shareHelper];
    if ([USER_D objectForKey:CurrentUserName])
    {
        self.window.rootViewController=_myTabBarVC;
        UINavigationController* conversationNav= [_myTabBarVC getItemNavgationControllerIndex:0];
        [FBDClientTool shareHelper].conversationListVC=[[conversationNav viewControllers] firstObject];
        [FBDClientTool shareHelper].appTabBarVC=[self fbd_tabBarVC];
        
    }else
    {
        self.window.rootViewController=_loginVC;
    }
    

    [self.window makeKeyAndVisible];
//    [self testFBD_FMDBTool];
    
    
//    EMOptions *options = [EMOptions optionsWithAppkey:HuanAPPKEY];
//    options.apnsCertName = HuanCenterAPNS;
//    [[EMClient sharedClient] initializeSDKWithOptions:options];
    [self fbd_Application:application registerAPNSWithOption:launchOptions];
//
//    // 用户注册
//    //    [self  appRegisterUser];
//    // 用户登录
//    [self appLoginUserName:HuanSheName  password:HuanMyselfPassword];
//    // 添加用户
//    [self addMyFriendWithId:@"bioons"];
//    //获取好友列表
////    [self  getAllMyFriends];
//    
//    
//    //设置代理
//    [[EMClient sharedClient].contactManager addDelegate:self
//                                          delegateQueue:nil];
    
    //初始化代理辅助类
    
    
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
    
        EMPushOptions* pushOption= [EMClient sharedClient].pushOptions;
        pushOption.displayStyle=EMPushDisplayStyleMessageSummary;
        [[EMClient sharedClient] updatePushOptionsToServer];
        
    });
 

    return YES;
}

//定位服务
-(void)beginLocationServer
{
    
    if([CLLocationManager locationServicesEnabled])
    {
        self.locationManage = [[CLLocationManager alloc] init] ;
        self.locationManage.distanceFilter = 200;
        self.locationManage.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//kCLLocationAccuracyBest;
        
        //使用期间
        [self.locationManage requestWhenInUseAuthorization];
        //始终
        //or [self.locationManage requestAlwaysAuthorization]
        
    }


}

#pragma mark ------------APNS通知
-(void)fbd_Application:(UIApplication *)application registerAPNSWithOption:(NSDictionary*)launchOption
{
    //iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }

}


#pragma mark - EMPushManagerDelegateDevice

// 打印收到的apns信息
-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo
                                                        options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *str =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.content", @"Apns content")
                                                    message:str
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
    
}


/**
 *      @author 冯宝东
 *
 *      环信注册用户
 */
-(void)appRegisterUser
{
    
    EMError *error = [[EMClient sharedClient] registerWithUsername:@"wangyulan" password:@"123456"];
    if (error==nil) {
        NSLog(@"注册成功");
    }else
    {
        NSLog(@"注册的描述信息：%@",error.errorDescription);
    
    }

}

/**
 *      @author 冯宝东
 *
 *      环信APP的用户登陆
 *
 *      @param user_Name     用户名
 *      @param user_Password 密码
 */
-(void)appLoginUserName:(NSString*)user_Name  password:(NSString*)user_Password
{
    EMError *error = [[EMClient sharedClient] loginWithUsername:user_Name  password:user_Password];
    if (!error)
    {
        [[EMClient sharedClient].options setIsAutoLogin:YES];//自动登陆
        NSLog(@"登录成功");
        [USER_D  setObject:user_Name forKey:CurrentUserName];
        [USER_D  synchronize];
        
    }else
    {
        NSLog(@"登录的描述信息：%@",error.errorDescription);
    
    }

}

// 添加好友
-(void)addMyFriendWithId:(NSString*)user_id
{
    EMError *error = [[EMClient sharedClient].contactManager addContact:user_id message:@"我想加您为好友"];
    if (!error) {
        NSLog(@"添加成功");
    }else
    {
        NSLog(@"添加添加失败：%@",error.errorDescription);
    
    }
    
//    [[EMClient sharedClient].contactManager asyncAddContact:user_id message:@"block 我想加你" success:^{
//        
//        NSLog(@"block 添加好友成功！");
//        
//    } failure:^(EMError *aError) {
//        NSLog(@"block 添加好友失败！");
//
//    }];

}

//同意添加好友
-(void)agreeAskForRequestWithUserId:(NSString*)user_id
{

    EMError *error = [[EMClient sharedClient].contactManager acceptInvitationForUsername:user_id];
    if (!error) {
        NSLog(@"发送成为好友同意成功");
    }else
    {
        NSLog(@"发送成为好友同意失败：%@",error.errorDescription);
    
    }

}


// 获取好友
-(NSArray*)getAllMyFriends
{

    EMError *error = nil;
    // 从服务器获取好友
    // NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromServerWithError:&error];
    //从数据库中获取好友
    NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromDB];
    if (!error) {
        NSLog(@"获取好友列表成功 -- %@",userlist);
    }else
    {
        NSLog(@"获取好友列表失败 -- %@",error.errorDescription);
    }

    return userlist;
}


/*!
 *  用户A发送加用户B为好友的申请，用户B会收到这个回调
 *
 *  @param aUsername   用户名
 *  @param aMessage    附属信息
 */
- (void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername
                                       message:(NSString *)aMessage
{

    NSString* showContent=[NSString stringWithFormat:@"%@ 要添加您为好友，你确定同意吗？",aUsername];
    [ShowAlertTool  showConfigeWithTitle:@"温馨提示" Message:showContent ButtonTitleArray:@[@"确定",@"取消"]];
    _agreeUserId=aUsername;
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:showContent delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"知道了", nil];
    
    [alertView show];



}

#pragma mark ----UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{


//    if (buttonIndex==0)
    {
        if (_agreeUserId)
        {
            [self agreeAskForRequestWithUserId:_agreeUserId];
        }

        
        
    }
    
    
    _agreeUserId=nil;
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}




-(void)configeNavgationBar
{
     [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          [UIColor whiteColor], NSForegroundColorAttributeName,
                                                          [UIFont fontWithName:@"AmericanTypewriter" size:20], NSFontAttributeName, nil]];
    NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor ],NSForegroundColorAttributeName, nil];
    [[UIBarButtonItem appearance] setTitleTextAttributes:dic forState:UIControlStateNormal];
    
   

}


-(void)configeIFlySpeech
{
    //设置log等级，此处log为默认在app沙盒目录下的msc.log文件
    [IFlySetting setLogFile:LVL_ALL];
    
    //输出在console的log开关
    [IFlySetting showLogcat:NO];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    //设置msc.log的保存路径
    [IFlySetting setLogFilePath:cachePath];
    
    
    //创建语音配置,appid必须要传入，仅执行一次则可
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@,timeout=%@",APPID_VALUE,TIMEOUT_VALUE];
    //所有服务启动前，需要确保执行createUtility
    [IFlySpeechUtility createUtility:initString];
    [IFlyFlowerCollector SetDebugMode:NO];
    [IFlyFlowerCollector SetCaptureUncaughtException:YES];
    [IFlyFlowerCollector SetAppid:APPID_VALUE];
    [IFlyFlowerCollector SetAutoLocation:YES];
    


}

-(void)testFBD_FMDBTool
{
       [FBD_FMDBTool   db_yxCreateDataBaseWithName:@"冯宝东"];
       [FBD_FMDBTool   db_yxCreateTableWithName:@"t_cityList"];
       NSMutableArray* listArray=[FBD_FMDBTool db_yxSearchTableViewName:@"t_cityList"];
       NSLog(@"listArray的个数是：%ld",(unsigned long)listArray.count);
       UIDevice* _myDevice=[UIDevice currentDevice];
    NSString* myLog=  [NSString stringWithFormat:@"%@:%@:%@:%@:%@>>>>>>>>>%f>>>>>>>%ld",_myDevice.name,_myDevice.model,_myDevice.systemName,_myDevice.systemVersion,_myDevice.identifierForVendor,_myDevice.batteryLevel,(long)_myDevice.userInterfaceIdiom];
    _myDevice.batteryMonitoringEnabled=YES;
    NSLog(@" myLog :%@",myLog);
    
    
}







// 设置本地通知
+ (void)registerLocalNotification:(NSInteger)alertTime {
   
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    // 设置触发通知的时间
    NSDate *fireDate = [NSDate date];
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.fireDate=[fireDate dateByAddingTimeInterval:alertTime];
    
    
    
    NSLog(@"fireDate=%@",fireDate);
    

    
    

    // 时区

    // 设置重复的间隔
//    notification.repeatInterval = NSCalendarUnitDay;
    
    // 通知内容
    notification.alertBody =  @"该起床了...";
    notification.applicationIconBadgeNumber = 1;
    // 通知被触发时播放的声音
    notification.soundName = UILocalNotificationDefaultSoundName;
    // 通知参数
    NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
    notification.userInfo = userDict;
    
    // ios8后，需要添加这个注册，才能得到授权
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    } else {
        // 通知重复提示的单位，可以是天、周、月
        notification.repeatInterval = NSCalendarUnitDay;
    }
    
    // 执行通知注册
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

// 本地通知回调函数，当应用程序在前台时调用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"noti:%@",notification);
    
    // 这里真实需要处理交互的地方
    // 获取通知所带的数据
//    NSString *notMess = [notification.userInfo objectForKey:@"key"];
    
    
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知(前台)"
//                                                    message:notMess
//                                                   delegate:nil
//                                          cancelButtonTitle:@"OK"
//                                          otherButtonTitles:nil];
//    [alert show];
    
    // 更新显示的徽章个数
    NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber;
    badge--;
    badge = badge >= 0 ? badge : 0;
    [UIApplication sharedApplication].applicationIconBadgeNumber = badge;
    
    [[self fbd_tabBarVC] setSelectedIndex:1];
    
//    [self performSelector:@selector(testAdjust) withObject:nil afterDelay:0.1];
    
}
-(void)testAdjust
{
    
    UINavigationController* mineNVC=[[[self fbd_tabBarVC] viewControllers]lastObject];
    
    
    MineViewController*mineVC=[mineNVC.viewControllers firstObject];
    
    
    [mineVC mineSubViewControllerWillToBePushIntoWithIndex:7];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
    [[EMClient sharedClient] applicationDidEnterBackground:application];

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

// 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
   
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
    
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error -- %@",error);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns)
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
//    [alert show];
    
    
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

}
@end
